﻿using System;

namespace Facebook
{
    public struct UnixDateTime
    {
        private const Double DIFF = 621355968000000000d;

        private const Double MULTIPLIER = 10000000d;

        public UnixDateTime(Double unixTime)
            : this()
        {
            this.Value = unixTime;
        }

        public UnixDateTime(Int64 unixTime)
            : this((Double)unixTime) { }

        public UnixDateTime(DateTime dateTime)
            : this(((Double)dateTime.Ticks - DIFF) / MULTIPLIER) { }

        public Double Value { get; set; }

        public DateTime ToDateTime()
        {
            return UnixDateTime.ToDateTime(this.Value);
        }

        public static DateTime ToDateTime(Double unixTime)
        {
            if (unixTime == 0) return DateTime.MinValue;
            else return new DateTime((Int64)((unixTime * MULTIPLIER) + DIFF), DateTimeKind.Utc);
        }

        public static Boolean TryParse(String input, out UnixDateTime unixDateTime)
        {
            Int64 value;
            if (Int64.TryParse(input, out value))
            {
                unixDateTime = new UnixDateTime(value);
                return true;
            }
            else
            {
                unixDateTime = new UnixDateTime(0);
                return false;
            }
        }

        public static UnixDateTime Now
        {
            get { return DateTime.Now.ToUnixDateTime(); }
        }

        public static implicit operator Int64(UnixDateTime unixDateTime)
        {
            return (Int64)unixDateTime.Value;
        }

        public static implicit operator Double(UnixDateTime unixDateTime)
        {
            return unixDateTime.Value;
        }

        public override String ToString()
        {
            return this.Value.ToString();
        }
    }
}